package com.smart.translator.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import com.smart.translator.device.BleDeviceManager;
import com.smart.translator.utils.KeyPositionUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ClipboardManager;

public class PasteAccessibilityService extends AccessibilityService {
    private static final String TAG = "PasteA11y";
    private static final long PASTE_DEBOUNCE_TIME = 1000L; // 1秒防抖
    private static final long CLICK_DELAY = 300; // 点击延迟
    private static final long PASTE_DELAY = 300; // 粘贴延迟
    
    public static final int GLOBAL_ACTION_PASTE = 1;
    
    public static volatile PasteAccessibilityService instance;
    private static long lastPasteTime = 0L;
    private static boolean pendingPaste = false;
    
    private volatile boolean isPasting = false;
    private Handler mainHandler;
    // 在 PasteAccessibilityService 类中
    public volatile boolean allowAutoAction = false;
    
    // 新增：延迟检查相关变量
    private Handler delayHandler = new Handler(Looper.getMainLooper());
    private Runnable delayedCheckRunnable;
    private static final long SEQUENCE_CHECK_DELAY = 200; // 200ms延迟
    
    // 支持多微信版本输入框ID
    private static final String[] WECHAT_EDITTEXT_IDS = {
        "com.tencent.mm:id/b4a",
        "com.tencent.mm:id/aaa",
        "com.tencent.mm:id/alz",
        "com.tencent.mm:id/aip"
        // 如有新ID可继续补充
    };

    private final BroadcastReceiver pasteReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive触发: 收到ACTION_TRIGGER_WECHAT_PASTE广播");
            new Handler().postDelayed(() -> {
                clickScreen(200, 2650);
                new Handler().postDelayed(PasteAccessibilityService.this::pasteToWechat, 500);
            }, 800);
        }
    };

    private ClipboardManager clipboardManager;
    private ClipboardManager.OnPrimaryClipChangedListener clipChangedListener;

    // 新增：键盘状态标志
    private boolean isWechatKeyboardShown = false;

    // 新增：事件匹配条件封装
    private static class EventPattern {
        final int type;
        final String pkg;
        final String cls;
        final String description;

        EventPattern(int type, String pkg, String cls, String description) {
            this.type = type;
            this.pkg = pkg;
            this.cls = cls;
            this.description = description;
        }

        boolean matches(AccessibilityEvent event) {
            boolean result = event.getEventType() == type &&
                   "com.tencent.mm".equals(event.getPackageName()) &&
                   cls.equals(event.getClassName());
            
            // 添加调试信息
            if (!result) {
                Log.d(TAG, "EventPattern匹配失败: 期望type=" + type + ", pkg=com.tencent.mm, cls=" + cls + 
                          "; 实际type=" + event.getEventType() + ", pkg=" + event.getPackageName() + ", cls=" + event.getClassName());
            }
            
            return result;
        }
    }

    // 新增：事件序列定义
    private static class EventSequence {
        final List<EventPattern> patterns;
        final long maxTimeWindow;
        final String name;

        EventSequence(List<EventPattern> patterns, long maxTimeWindow, String name) {
            this.patterns = patterns;
            this.maxTimeWindow = maxTimeWindow;
            this.name = name;
        }
    }

    // 新增：事件缓存
    private static class CachedEvent {
        final AccessibilityEvent event;
        final long timestamp;

        CachedEvent(AccessibilityEvent event) {
            this.event = event;
            this.timestamp = System.currentTimeMillis();
        }
    }

    // 新增：事件序列匹配器
    private static class EventSequenceMatcher {
        private final List<CachedEvent> eventCache = new ArrayList<>();
        private final List<EventSequence> sequences;
        private static final int MAX_CACHE_SIZE = 10;
        private String lastMatchedSequenceName = null;  // 新增：保存最后匹配的序列名称

        EventSequenceMatcher(List<EventSequence> sequences) {
            this.sequences = sequences;
        }

        void addEvent(AccessibilityEvent event) {
            // 清理过期事件
            long currentTime = System.currentTimeMillis();
            boolean hasExpiredEvent = eventCache.removeIf(e -> currentTime - e.timestamp > 1000);
            
            // 如果有过期事件，清空整个队列，避免积累无用数据
            if (hasExpiredEvent) {
                Log.d(TAG, "检测到过期事件，清空整个队列");
                eventCache.clear();
            }

            // 添加新事件，实现循环队列
            if (eventCache.size() >= MAX_CACHE_SIZE) {
                eventCache.remove(0); // 移除最旧的事件
            }
            eventCache.add(new CachedEvent(event));
        }

        boolean checkSequences() {
            Log.d(TAG, "开始检查事件序列，当前缓存事件数量: " + eventCache.size());
            
            for (EventSequence sequence : sequences) {
                if (matchSequence(sequence)) {
                    Log.d(TAG, "匹配到事件序列: " + sequence.name + " (长度: " + sequence.patterns.size() + ")");
                    lastMatchedSequenceName = sequence.name;  // 保存匹配的序列名称
                    // 匹配成功后清空队列
                    eventCache.clear();
                    return true;
                }
            }
            
            Log.d(TAG, "未匹配到任何事件序列，清空队列");
            // 未匹配到任何序列时也清空队列，避免积累过多无用数据
            eventCache.clear();
            return false;
        }

        private boolean matchSequence(EventSequence sequence) {
            if (eventCache.size() < sequence.patterns.size()) {
                //Log.d(TAG, "序列 " + sequence.name + " 匹配失败：缓存事件数量(" + eventCache.size() + ") < 序列长度(" + sequence.patterns.size() + ")");
                return false;
            }

            // 获取最近的事件，数量等于序列模式的数量
            List<CachedEvent> recentEvents = eventCache.subList(
                eventCache.size() - sequence.patterns.size(),
                eventCache.size()
            );

            // 检查时间窗口
            if (recentEvents.get(recentEvents.size() - 1).timestamp - 
                recentEvents.get(0).timestamp > sequence.maxTimeWindow) {
                //Log.d(TAG, "序列 " + sequence.name + " 匹配失败：时间窗口超时");
                // 时间窗口超时时清空队列
                eventCache.clear();
                return false;
            }

            // 检查事件序列前缀匹配
            for (int i = 0; i < sequence.patterns.size(); i++) {
                EventPattern pattern = sequence.patterns.get(i);
                AccessibilityEvent event = recentEvents.get(i).event;
                
                //Log.d(TAG, "序列 " + sequence.name + " 第" + (i+1) + "个事件匹配检查:");
                //Log.d(TAG, "  期望: EventType=" + pattern.type + ", Package=" + pattern.pkg + ", Class=" + pattern.cls);
                //Log.d(TAG, "  实际: EventType=" + event.getEventType() + ", Package=" + event.getPackageName() + ", Class=" + event.getClassName());
                
                if (!pattern.matches(event)) {
                    //Log.d(TAG, "序列 " + sequence.name + " 匹配失败：第" + (i+1) + "个事件不匹配");
                    return false;
                }
            }
            
            Log.d(TAG, "序列 " + sequence.name + " 匹配成功！");
            return true;
        }

        // 修改：获取最后匹配的序列名称
        String getLastMatchedSequence() {
            return lastMatchedSequenceName;
        }

        // 新增：清空最后匹配的序列名称
        void clearLastMatchedSequence() {
            lastMatchedSequenceName = null;
        }

        // 新增：获取当前队列大小
        int getQueueSize() {
            return eventCache.size();
        }

        // 新增：清空队列
        void clearQueue() {
            eventCache.clear();
            clearLastMatchedSequence();  // 同时清空最后匹配的序列名称
        }
    }

    // 新增：键盘触发序列定义
    private static final EventSequence KEYBOARD_SHOW_SEQUENCE = new EventSequence(
        Arrays.asList(
            new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
            new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
            new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1"),
            new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化2")
        ),
        500, // 500ms时间窗口
        "键盘显示序列"
    );

    private static final EventSequence KEYBOARD_SHOW_SEQUENCE1 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(32, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化")
//                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1"),
//                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化2")
            ),
            500, // 500ms时间窗口
            "键盘显示序列"
    );

    // 新增：调试用的键盘触发序列定义
    private static final EventSequence KEYBOARD_SHOW_SEQUENCE1_DEBUG = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(32, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
                    new EventPattern(2048, "com.tencent.mm", "androidx.recyclerview.widget.RecyclerView", "RecyclerView变化")
            ),
            500, // 500ms时间窗口
            "键盘显示序列调试"
    );

    private static final EventSequence KEYBOARD_SHOW_SEQUENCE2 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(32, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化2")
            ),
            500, // 500ms时间窗口
            "键盘显示序列"
    );


    private static final EventSequence KEYBOARD_SHOW_SEQUENCE3 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化2")
            ),
            500, // 500ms时间窗口
            "键盘显示序列"
    );


    // 新增：键盘触发序列定义
    private static final EventSequence KEYBOARD_SHOW_SEQUENCE4 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1")
            ),
            500, // 500ms时间窗口
            "键盘显示序列"
    );

    // 新增：键盘触发序列定义
    private static final EventSequence KEYBOARD_SHOW_SEQUENCE5 = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化"),
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "输入框点击"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "FrameLayout变化")
            ),
            500, // 500ms时间窗口
            "键盘显示序列"
    );


    // KEYBOARD_SHOW_SEQUENCE
    private static final EventSequence Keyboard_show_sequence6 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "说明1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "说明2"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "说明3"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "说明4")
                    //new EventPattern(2048, "com.tencent.mm", "android.view.ViewGroup", "说明5")
            ),
            500,
            "KEYBOARD_SHOW_SEQUENCE"
    );
    private static final EventSequence Keyboard_show_sequence7 = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.EditText", "说明1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "说明3"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "说明4")
            ),
            500,
            "KEYBOARD_SHOW_SEQUENCE"
    );


    // 新增：键盘未触发序列定义
    private static final EventSequence EVENT_NONE_SHOW_SEQUENCE = new EventSequence(
        Arrays.asList(
            new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LinearLayout变化1"),
            new EventPattern(32, "com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "LauncherUI变化")
        ),
        500, // 500ms时间窗口
        "执行后未触发edittext序列"
    );

    // 新增：键盘未触发序列定义
    private static final EventSequence EVENT_NONE_SHOW1_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(32, "com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "LauncherUI变化")
            ),
            500, // 500ms时间窗口
            "执行后未触发edittext序列"
    );

    // 新增：触发返回未触发序列定义
    private static final EventSequence EVENT_NONE_SHOW2_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(32, "com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(32, "com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1")
            ),
            500, // 500ms时间窗口
            "执行后未触发edittext序列"
    );

    // 新增：触发返回未触发序列定义
    private static final EventSequence EVENT_NONE_SHOW3_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(32, "com.tencent.mm", "com.tencent.mm.ui.LauncherUI", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1")//,
                    //new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1")
            ),
            500, // 500ms时间窗口
            "执行后未触发edittext序列"
    );

    // 新增：触发返回未触发序列定义
    private static final EventSequence EVENT_SENDMSG_SHOW_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(1, "com.tencent.mm", "android.widget.Button", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LauncherUI变化")
            ),
            500, // 500ms时间窗口
            "执行按钮触发发送消息序列"
    );

    // 新增：触发返回未触发序列定义
    private static final EventSequence EVENT_TRTURN_SHOW_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LauncherUI变化")

            ),
            500, // 500ms时间窗口
            "执行后触发返回序列"
    );

    // 新增：触发返回未触发序列定义
    private static final EventSequence KEYBOARD_MASTER_HIDE_SEQUENCE = new EventSequence(
            Arrays.asList(
                    new EventPattern(2048, "com.tencent.mm", "android.widget.FrameLayout", "LinearLayout变化1"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LauncherUI变化"),
                    new EventPattern(2048, "com.tencent.mm", "android.widget.LinearLayout", "LauncherUI变化")

            ),
            500, // 500ms时间窗口
            "执行主动关闭键盘 触发序列"
    );


    // 修正：事件序列匹配器实例
    private final EventSequenceMatcher eventMatcher = new EventSequenceMatcher(
        Arrays.asList(
                KEYBOARD_SHOW_SEQUENCE,
                KEYBOARD_SHOW_SEQUENCE1,
                KEYBOARD_SHOW_SEQUENCE1_DEBUG,
                KEYBOARD_SHOW_SEQUENCE2,
                KEYBOARD_SHOW_SEQUENCE3,
                KEYBOARD_SHOW_SEQUENCE4,
                KEYBOARD_SHOW_SEQUENCE5,
                Keyboard_show_sequence6,
                Keyboard_show_sequence7,


                EVENT_NONE_SHOW_SEQUENCE,
                EVENT_NONE_SHOW1_SEQUENCE,
                EVENT_NONE_SHOW2_SEQUENCE,
                EVENT_NONE_SHOW3_SEQUENCE,


                EVENT_TRTURN_SHOW_SEQUENCE,
                EVENT_SENDMSG_SHOW_SEQUENCE,
                KEYBOARD_MASTER_HIDE_SEQUENCE)
    );

    public static void triggerPaste(Context context) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastPasteTime < PASTE_DEBOUNCE_TIME) {
            Log.d(TAG, "防抖期内，标记待处理");
            pendingPaste = true;
            return;
        }
        
        if (instance != null) {
            instance.performPaste();
            lastPasteTime = currentTime;
        } else {
            Log.d(TAG, "服务未启动，发送广播");
            Intent intent = new Intent("ACTION_TRIGGER_WECHAT_PASTE");
            context.sendBroadcast(intent);
        }
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        mainHandler = new Handler(Looper.getMainLooper());
    }
    
    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        Log.d(TAG, "onServiceConnected: PasteAccessibilityService已启动");
        if (pendingPaste) {
            Log.d(TAG, "执行待处理的粘贴请求");
            performPaste();
            pendingPaste = false;
        }
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        instance = null;
        Log.d(TAG, "无障碍服务已断开");
        return super.onUnbind(intent);
    }
    
    private void performPaste() {
        if (isPasting) {
            Log.d(TAG, "粘贴操作正在进行中，忽略本次请求");
            return;
        }
        isPasting = true;
        Log.d(TAG, "开始执行粘贴操作");

        float clickX, clickY, afterX, afterY;
        if (!isWechatKeyboardShown) {
            // 未触发键盘，先点击下方输入框
            clickX = 200;
            clickY = 2650;

            afterX = 1050;
            afterY = 1500;

        } else {
            // 已触发键盘，点击上方输入框
            clickX = 200;
            clickY = 1500;
            afterX = 1100;
            afterY = 2650;
        }

        // 创建点击手势
        Path clickPath = new Path();
        clickPath.moveTo(clickX, clickY);
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(new GestureDescription.StrokeDescription(clickPath, 0, 100));

        dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                Log.d(TAG, "点击聚焦完成，准备粘贴");
                mainHandler.postDelayed(() -> {
                    performGlobalAction(GLOBAL_ACTION_PASTE);
                    Log.d(TAG, "已自动粘贴");
                    // 粘贴后再点击一次指定坐标
                    mainHandler.postDelayed(() -> {
                        clickScreen((int) afterX, (int) afterY);
                        isPasting = false;
                        if (pendingPaste) {
                            Log.d(TAG, "执行新的待处理粘贴请求");
                            pendingPaste = false;
                            performPaste();
                        }
                    }, 500);
                }, PASTE_DELAY);
            }
            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                Log.d(TAG, "点击手势被取消");
                isPasting = false;
            }
        }, null);
    }
    
    private float getAdaptedX() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        return Math.max(metrics.widthPixels * 0.1f, 100f);
    }
    
    private float getAdaptedY() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        return Math.min(metrics.heightPixels * 0.9f, metrics.heightPixels - 100f);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int type = event.getEventType();
        CharSequence pkg = event.getPackageName();
        CharSequence cls = event.getClassName();

        Log.d(TAG, "EventType=" + type + ", Package=" + pkg + ", Class=" + cls);

        // 新增：事件序列匹配
        eventMatcher.addEvent(event);
        
        // 取消之前的延迟检查
        if (delayedCheckRunnable != null) {
            delayHandler.removeCallbacks(delayedCheckRunnable);
        }
        
        // 创建新的延迟检查任务
        delayedCheckRunnable = new Runnable() {
            @Override
            public void run() {
                if (eventMatcher.checkSequences()) {
                    String matchedSequence = eventMatcher.getLastMatchedSequence();
                    Log.d(TAG, "检测到事件序列: " + matchedSequence);
                    
                    // 根据匹配的序列类型设置键盘状态
                    if ((KEYBOARD_SHOW_SEQUENCE.name.equals(matchedSequence) ||
                            (KEYBOARD_SHOW_SEQUENCE1.name.equals(matchedSequence)) ||
                            (KEYBOARD_SHOW_SEQUENCE2.name.equals(matchedSequence)) ||
                            (KEYBOARD_SHOW_SEQUENCE3.name.equals(matchedSequence))  ||
                            (KEYBOARD_SHOW_SEQUENCE4.name.equals(matchedSequence))  ||
                            (KEYBOARD_SHOW_SEQUENCE5.name.equals(matchedSequence))  ||
                            (Keyboard_show_sequence6.name.equals(matchedSequence))  ||
                            (Keyboard_show_sequence7.name.equals(matchedSequence)) ||

                            (KEYBOARD_SHOW_SEQUENCE1_DEBUG.name.equals(matchedSequence))




                            )) {
                        isWechatKeyboardShown = true;

                        if(allowAutoAction) {
                            new android.os.Handler().postDelayed(() -> {
                                PasteAccessibilityService.instance.pasteToWechat();
                            }, 500);

                            DisableAutoActionOnce();
                        }
                    } //检测未唤醒键盘重新发送触摸事件
                    else if (EVENT_NONE_SHOW_SEQUENCE.name.equals(matchedSequence) ||
                            (EVENT_NONE_SHOW1_SEQUENCE.name.equals(matchedSequence)) ||
                            (EVENT_NONE_SHOW2_SEQUENCE.name.equals(matchedSequence)) ||
                            (EVENT_NONE_SHOW3_SEQUENCE.name.equals(matchedSequence))



                    ) {

                        //重新发送唤醒键盘触摸事件
                        clickWechatInputByKeyboardState();
                        isWechatKeyboardShown = false;
                        new android.os.Handler().postDelayed(() -> {
                             PasteAccessibilityService.instance.pasteToWechat();
                         }, 500);
                    }
                    //执行返回操作
                    else if(EVENT_TRTURN_SHOW_SEQUENCE.name.equals(matchedSequence)){
                        isWechatKeyboardShown = false;
                    }
                    //执行主动隐藏键盘操作
                    else if(KEYBOARD_MASTER_HIDE_SEQUENCE.name.equals(matchedSequence)){
                        isWechatKeyboardShown = false;

                        if(allowAutoAction) {
                            new android.os.Handler().postDelayed(() -> {
                                PasteAccessibilityService.instance.pasteToWechat();
                            }, 500);
                            DisableAutoActionOnce();
                        }
                    }
                }
            }
        };
        
        // 延迟200ms执行检查
        delayHandler.postDelayed(delayedCheckRunnable, SEQUENCE_CHECK_DELAY);

        // 微信输入框聚焦，推测键盘弹出
        // if (type == AccessibilityEvent.TYPE_VIEW_CLICKED &&
        //     "com.tencent.mm".contentEquals(pkg) &&
        //     "android.widget.EditText".contentEquals(cls)) {
        //     Log.d(TAG, "微信输入框聚焦，推测键盘弹出");
        //     isWechatKeyboardShown = true;
        // }

        // // 微信窗口内容变化，推测键盘收回
        // if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED &&
        //     "com.tencent.mm".contentEquals(pkg)) {
        //     Log.d(TAG, "微信窗口状态变化，可能键盘收回");
        //     isWechatKeyboardShown = false;
        // }

        // 原有的其他逻辑保持不变
//        new android.os.Handler().postDelayed(() -> {
//             PasteAccessibilityService.instance.pasteToWechat();
//         }, 500);
    }

    public void pasteToWechat() {
        Log.d(TAG, "准备执行 pasteToWechat，当前线程：" + Thread.currentThread().getName());
        Log.d(TAG, "通过BLE下发粘贴命令");
        boolean result = BleDeviceManager.getInstance().writeData(new byte[]{0x01});
        Log.d(TAG, "BLE粘贴命令下发结果: " + result);

        // 延时 3 秒执行任务
        new android.os.Handler().postDelayed(() -> {
            Log.d("MyService", "延时后执行任务");
            // TODO: 在这里执行你的操作

            // 获取当前应用包名
            String appPackage = getCurrentAppPackage();
            //点击发送消息按钮
            if (instance.isWechatKeyboardShown) {


                KeyPositionUtils.Point buttonPos = KeyPositionUtils.getButtonPositionByPackage(
                        instance, appPackage, KeyPositionUtils.ID_SEND_WITH_IME);
                if (buttonPos != null) {

                    Log.d(TAG,"获取到微信调起输入法点击发送按钮位置");
                    instance.clickScreen(buttonPos.x, buttonPos.y);
                } else {
                     instance.clickScreen(1100, 1500);
                    Log.d(TAG, "使用 默认 键盘唤起 点击发送消息按钮: " + result);
                }

            } else {


                KeyPositionUtils.Point buttonPos = KeyPositionUtils.getButtonPositionByPackage(
                        instance, appPackage, KeyPositionUtils.ID_SEND_NO_IME);
                if (buttonPos != null) {

                    Log.d(TAG,"获取到微信未调起输入法点击发送按钮位置");
                    instance.clickScreen(buttonPos.x, buttonPos.y);
                } else {
                    instance.clickScreen(1100, 2600);
                    Log.d(TAG, "使用 默认 键盘未唤起 点击发送消息按钮: " + result);
                }
            }
        }, 500);



       // clickScreen(1100, 1500);

    }

    // 递归打印所有节点信息
    private void printAllNodes(AccessibilityNodeInfo node, int depth) {
        if (node == null) return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < depth; i++) sb.append("  ");
        sb.append("class: ").append(node.getClassName())
          .append(", text: ").append(node.getText())
          .append(", id: ").append(node.getViewIdResourceName());
        Log.d(TAG, sb.toString());
        for (int i = 0; i < node.getChildCount(); i++) {
            printAllNodes(node.getChild(i), depth + 1);
        }
    }

    // 递归查找所有EditText节点
    private List<AccessibilityNodeInfo> findAllEditTexts(AccessibilityNodeInfo root) {
        List<AccessibilityNodeInfo> result = new ArrayList<>();
        if (root == null) return result;
        if ("android.widget.EditText".contentEquals(root.getClassName())) {
            result.add(root);
        }
        for (int i = 0; i < root.getChildCount(); i++) {
            result.addAll(findAllEditTexts(root.getChild(i)));
        }
        return result;
    }

    // 新增：递归查找所有com.tencent.mm.ui.widget.MMEditText节点
    private List<AccessibilityNodeInfo> findAllMMEditTexts(AccessibilityNodeInfo root) {
        List<AccessibilityNodeInfo> result = new ArrayList<>();
        if (root == null) return result;
        if ("com.tencent.mm.ui.widget.MMEditText".contentEquals(root.getClassName())) {
            result.add(root);
        }
        for (int i = 0; i < root.getChildCount(); i++) {
            result.addAll(findAllMMEditTexts(root.getChild(i)));
        }
        return result;
    }

    // 自动点击屏幕指定坐标
    public void clickScreen(int x, int y) {
        // 仅 Android N 及以上支持 dispatchGesture
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return;

        // 构造点击路径
        Path path = new Path();
        path.moveTo(x, y);

        // 延迟 0ms，持续 100ms
        GestureDescription.StrokeDescription stroke =
                new GestureDescription.StrokeDescription(path, 0, 100);
        GestureDescription gesture = new GestureDescription.Builder()
                .addStroke(stroke)
                .build();

        // 分发手势并打印回调，方便调试
        dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                Log.d(TAG, "clickScreen: 手势执行完成");
            }
            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                Log.w(TAG, "clickScreen: 手势被取消");
            }
        }, null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
        Log.d(TAG, "onDestroy: PasteAccessibilityService销毁");
        
        // 清理延迟检查任务
        if (delayedCheckRunnable != null) {
            delayHandler.removeCallbacks(delayedCheckRunnable);
            delayedCheckRunnable = null;
        }
        
        // 注销剪贴板监听
        if (clipboardManager != null && clipChangedListener != null) {
            clipboardManager.removePrimaryClipChangedListener(clipChangedListener);
            Log.d(TAG, "PasteAccessibilityService已注销剪贴板监听");
        }
    }

    @Override
    public void onInterrupt() {
        Log.d(TAG, "onInterrupt");
    }

    public static void clickWechatInputByKeyboardState() {
        if (instance == null) return;
        
        // 获取当前应用包名
        String appPackage = getCurrentAppPackage();
        
        if (instance.isWechatKeyboardShown) {
            Log.d(TAG, "clickWechatInputByKeyboardState isWechatKeyboardShown true");

            KeyPositionUtils.Point buttonPos = KeyPositionUtils.getButtonPositionByPackage(
                instance, appPackage, KeyPositionUtils.ID_INPUT_WITH_IME);
            if (buttonPos != null) {

                Log.d(TAG,"获取到微信调起输入法点击输入框按钮位置");
                instance.clickScreen(buttonPos.x, buttonPos.y);
            } else {
                // 如果未找到配置的按钮位置，使用默认位置
                instance.clickScreen(400, 1500);
                Log.d(TAG,"未获取到微信调起输入法点击输入框按钮位置 使用默认");
            }
        } else {
            Log.d(TAG, "clickWechatInputByKeyboardState isWechatKeyboardShown false");

            KeyPositionUtils.Point buttonPos = KeyPositionUtils.getButtonPositionByPackage(
                    instance, appPackage, KeyPositionUtils.ID_INPUT_NO_IME);
            if (buttonPos != null) {
                Log.d(TAG,"获取到微信未调起输入法点击输入框按钮位置");
                        instance.clickScreen(buttonPos.x, buttonPos.y);
            } else {
                Log.d(TAG,"未获取到微信未调起输入法点击输入框按钮位置 使用默认");

                // 如果未找到配置的按钮位置，使用默认位置
                instance.clickScreen(400, 2650);
            }
        }
    }
    
    /**
     * 获取当前应用包名
     */
    private static String getCurrentAppPackage() {
        if (instance != null) {
            // 尝试从AccessibilityService获取当前包名
            try {
                // 这里可以根据实际需求获取当前应用包名
                // 暂时返回微信包名作为默认值
                return "com.tencent.mm";
            } catch (Exception e) {
                Log.e(TAG, "获取当前应用包名失败", e);
                return "com.tencent.mm"; // 默认返回微信包名
            }
        }
        return "com.tencent.mm"; // 默认返回微信包名
    }

    // 新增方法，供Receiver调用
    public void enableAutoActionOnce() {
        allowAutoAction = true;
    }

    // 新增方法，供Receiver调用
    public void DisableAutoActionOnce() {
        allowAutoAction = false;
    }

} 
